package com.leapp.sk.viewdelegate

import android.app.Activity
import android.content.Intent
import android.text.TextUtils
import android.view.View
import android.widget.AbsListView
import android.widget.ListView
import android.widget.TextView
import cc.vv.lkbasecomponent.util.LKStringUtil
import cc.vv.lkimcomponent.lkim.bean.LKIMConversation
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMChatType
import cc.vv.lkimcomponent.lkim.operate.LKIMEdit
import com.example.baselibrary.db.dao.GroupDao
import com.example.mvp.delegate.BaseAppDelegate
import com.example.mvp.view.DialogListView
import com.example.mvp.view.LKDialog
import com.leapp.sk.R
import com.example.mvp.view.SKTopBar
import com.leapp.sk.app.SKApplication
import com.example.im.IMConversationOperate
import com.leapp.sk.ui.activity.AppMainTableActivity
import com.leapp.sk.ui.activity.im.GroupChatActivity
import com.leapp.sk.ui.activity.im.SingleChatActivity
import com.leapp.sk.ui.activity.notify.NotifyActivity
import com.leapp.sk.ui.adapter.MessageListAdapter
import com.example.im.server.im.IMChatService
import com.example.util.finallist.*

import com.example.baselibrary.db.dao.AccountDao
import com.example.util.IntegerUtil


/**
 * 消息主界面视图托管
 * @author  chaohaipeng  on 2018/7/2.
 */
class MessageDelegate : BaseAppDelegate() {

    var mAdapter: MessageListAdapter? = null
    override fun initWidget() {
    }

    override fun initLayoutRes(): Int {
        return R.layout.fragment_message_list
    }

    /**
     * 控制无网络view的显隐
     *
     * @param isShow
     */
    fun controlNoNetView(isShow:Boolean) {
        val tv_fml_noNetWork = getView<TextView>(R.id.tv_fml_noNetWork)
        if (isShow){
            tv_fml_noNetWork.visibility=View.VISIBLE
        }else{
            tv_fml_noNetWork.visibility=View.GONE
        }

    }


    /**
     * 设置标题
     */
    fun setTitle(title: String?) {
        val topBar = getView<SKTopBar>(R.id.jtb_fml)
        topBar.rl_ljtb_left_layout?.visibility = View.GONE
        if (!TextUtils.isEmpty(title)) {
            topBar?.setTitle(title)
        }
    }
    /**
     * 初始化适配器
     */
    fun initAdapter(context: Activity, mIMConversation: MutableList<LKIMConversation>) {
        val lv_fml = getView<ListView>(R.id.lv_fml)
        mAdapter = MessageListAdapter(context, mIMConversation)
        lv_fml.adapter = mAdapter
        lv_fml.setOnItemClickListener { adapterView, view, i, l ->
            val get = mIMConversation.get(i)
            val messageType = get.getAttribute(IMExtKey.EXTKEY_MESSAGETYPE,"")
          val conversationId=  get.conversationId
              //系统消息
            if (TextUtils.equals(SkKey.SK_SYSTEM_MSG,conversationId)) {
                val intent: Intent = Intent(getActivity(), NotifyActivity::class.java)
                getActivity<AppMainTableActivity>().startActivity(intent)
            }else{
                if (get.lkimChatType == LKIMChatType.SingleChat) {
                    val conversationId = get.conversationId
                    val accountTable = AccountDao.getInstance().queryById(conversationId)
                    val nick = if (null == accountTable) LKStringUtil.getString(R.string.app_name) else accountTable.nick
                    val intent: Intent = Intent(getActivity(), SingleChatActivity::class.java)
                    intent.putExtra(MESSAGE_LIST_ID, get.conversationId)
                    intent.putExtra(TECHER_NICK,nick)
                    getActivity<AppMainTableActivity>().startActivity(intent)
                } else {
                    val groupTable = GroupDao.getInstance().queryById(get.conversationId)
                    val intent: Intent = Intent(getActivity(), GroupChatActivity::class.java)
                    intent.putExtra(GROUP_NAME, groupTable.groupNick)
                    intent.putExtra(MESSAGE_LIST_ID, get.conversationId)
                    getActivity<AppMainTableActivity>().startActivity(intent)
                }
            }
            setAllRead(get.conversationId)
        }

        lv_fml.setOnItemLongClickListener { adapterView, view, position, l ->
            try {
                val imConversation = mIMConversation?.get(position)
                val top = imConversation.getAttribute(IMExtKey.EXTKEY_TOP, SkKey.BTKEY_String_0)
                val dialogListObjs = IMChatService.getInstance().initIMFDialog(TextUtils.equals(SkKey.BTKEY_String_1, top), false)
                DialogListView.getInstance().initDialog(context, dialogListObjs, object : DialogListView.OperateInter {
                    override fun onItemClick(dialogListObj: DialogListView.DialogListObj) {
                        if (SkKey.BTKEY_INT_0 === dialogListObj.type) {
                            IMConversationOperate.getInstance().editTopExt(imConversation)
                            IMConversationOperate.getInstance().conversationsSort(mIMConversation)
                            mAdapter?.notifyDataSetChanged()
                        } else if (SkKey.BTKEY_INT_1 === dialogListObj.type) {
                            /**
                             * 删除指定会话
                             */
                            val lkDialog = LKDialog(context)
                            lkDialog.setMessage(LKStringUtil.getString(R.string.string_im_deleteHint))
                            lkDialog.setLeftButton(LKStringUtil.getString(R.string.app_cancel), View.OnClickListener { lkDialog.dismiss() })
                            lkDialog.setRightButton(LKStringUtil.getString(R.string.app_confirm), View.OnClickListener {
                                lkDialog.dismiss()
                                mIMConversation.remove(imConversation)
                                mAdapter?.notifyDataSetChanged()
                                LKIMEdit.getInstance().delete(imConversation.getConversationId())
                            })
                            lkDialog.show()
                        }
                    }
                })
            } catch (e: Exception) {
                e.printStackTrace()
            }
            true
        }
    }


    fun initEvent(){
        val lv_fml = getView<ListView>(R.id.lv_fml)
        val tv_fml_initView = getView<TextView>(R.id.tv_fml_initView)
        val tv_fml_scrollView = getView<TextView>(R.id.tv_fml_scrollView)
        lv_fml.setOnScrollListener(object :AbsListView.OnScrollListener{
            override fun onScroll(p0: AbsListView?, p1: Int, p2: Int, p3: Int) {
                SKApplication.getInstance()?.mHandler?.post(object:Runnable{
                    override fun run() {
                        if (p1>=1){
                            tv_fml_initView.visibility=View.GONE
                            tv_fml_scrollView.visibility=View.VISIBLE
                        }else{
                            tv_fml_initView.visibility=View.VISIBLE
                            tv_fml_scrollView.visibility=View.INVISIBLE

                        }
                    }
                })

            }
            override fun onScrollStateChanged(p0: AbsListView?, p1: Int) {
            }

        })

    }



    /**
     * 异步处理未读
     *
     * @param conversationId
     */
    private fun setAllRead(conversationId: String) {
        Thread(Runnable { LKIMEdit.getInstance().setAllRead(conversationId) }).start()
    }

    /**
     * 刷新适配器
     */
    fun notifyAdapter() {
        mAdapter?.notifyDataSetChanged()

    }

}